<template>
  <div class="white-list feature-out">
    <div ref="searchDiv" class="filter-container">
      <el-input
        v-model="tableQuery.name"
        style="width: 200px;"
        placeholder="请输入类型名称"
        size="small"
        class="filter-item"
      ></el-input>

      <el-input
        v-model="tableQuery.number"
        style="width: 200px;"
        placeholder="请输入编号"
        size="small"
        class="filter-item"
      ></el-input>

      <el-button
        size="small"
        @click="handleFilter"
        type="primary"
        class="filter-item"
        ref="btnQuery"
      >
        查询
      </el-button>
      <el-button
        @click="handleReset"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
      >
        重置
      </el-button>
      <el-button
        @click="handleType('add')"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
      >
        新增名单类型
      </el-button>
    </div>

    <el-table
      :data="tableData"
      :max-height="tableHeight"
      style="width: 100%;margin-bottom: 12px;"
    >
      <el-table-column
        label="类型名称"
        prop="name"
        align="center"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="编号"
        prop="number"
        align="center"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="备注"
        prop="remark"
        align="center"
        min-width="180px"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createdAt"
        align="center"
        width="180px"
      >
      </el-table-column>
      <el-table-column
        label="更新时间"
        prop="updatedAt"
        align="center"
        width="180px"
      >
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="100px">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="handleType('update', scope.row)"
          >
            编辑
          </el-button>
          <el-button type="text" size="mini" @click="deleteType(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="tableQuery.page"
        :page-sizes="[10, 20, 50]"
        :page-size="tableQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      class="new-dialog"
      width="400px"
    >
      <el-form
        class="small-space"
        label-position="right"
        label-width="80px"
        :model="createdItem"
        :rules="rules"
        ref="featureForm"
        style="width: 90%; margin-left:0px;"
      >
        <el-form-item prop="name" label="类型名称">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.name"
            placeholder="请输入名单类型"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="number" label="编号">
          <el-input
            size="small"
            type="text"
            :disabled="actionType === 'update'"
            v-model="createdItem.number"
            placeholder="请输入类型编号"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input
            size="small"
            type="textarea"
            v-model="createdItem.remark"
            placeholder="请输入备注信息"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="formVisible = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, update, del } from '@/api/risksystem/roster/listType'
import { Form, Table } from 'element-ui'

const defaultPage = {
  limit: 10,
  page: 1
}
const defaultQuery = {
  id: '',
  name: '',
  remark: '',
  number: ''
}

export default {
  components: {},
  data() {
    return {
      title: '',
      statusArr: {
        '1': '有效',
        '2': '无效'
      },
      tableQuery: Object.assign({}, defaultQuery, defaultPage),
      total: 0,
      tableData: [],
      tableHeight: null,
      tableLoading: true,
      createdItem: Object.assign({}, defaultQuery),
      actionType: 'add',
      formVisible: false,
      formSubmiting: false,
      rules: {
        name: [{ required: true, message: '请填写类型名称', trigger: 'blur' }],
        number: [{ required: true, message: '请填写编号', trigger: 'blur' }],
        remark: [{ required: true, message: '请填写备注', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {
    datePicker() {
      this.createdItem.effect_time_start = this.datePicker
        ? this.datePicker[0]
        : ''
      this.createdItem.effect_time_end = this.datePicker
        ? this.datePicker[1]
        : ''
    }
  },
  mounted() {
    this.getList()
    this.init()
  },
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  },
  methods: {
    // 表格高度
    init() {
      var _this = this
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - this.$refs.searchDiv.offsetHeight - 230
      })
      window.onresize = () => {
        this.$nextTick(() => {
          this.tableHeight =
            window.innerHeight - this.$refs.searchDiv.offsetHeight - 230
        })
      }
    },
    getList() {
      this.tableLoading = true
      list({ search: this.tableQuery }).then(response => {
        if (response.code === 0) {
          this.tableData = response.data.rows
          this.total = Number(response.data.count)
        }
      })
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.tableQuery = Object.assign({}, defaultQuery)
      this.getList()
    },
    handleSizeChange(val) {
      this.tableQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.tableQuery.page = val
      this.getList()
    },

    // 新增|编辑
    handleType(action, data = {}) {
      if (action === 'add') {
        data = Object.assign({}, defaultQuery)
        this.datePicker = ''
        this.title = '新增名单类型'
      } else {
        this.title = '编辑名单类型'
      }
      this.actionType = action
      Object.assign(this.createdItem, data)
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs['featureForm'].clearValidate()
      })
    },
    // 删除
    deleteType(id) {
      this.$confirm('确认删除该名单类型？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del({ id: id }).then(response => {
            if (response.code === 0) {
              this.$message.success('删除成功！')
              this.getList()
            } else {
              this.$message.success(response.msg)
            }
          })
        })
        .catch(() => {})
    },
    // 保存
    save() {
      this.$refs['featureForm'].validate(valid => {
        if (valid) {
          let action = this.actionType
          let data = {}
          if (action === 'add') {
            for (let i in defaultQuery) {
              data[i] = this.createdItem[i]
            }
            add(data).then(response => {
              this.formVisible = false
              this.$message.success('操作成功')
              this.getList()
            })
          } else {
            data.id = this.createdItem.id
            data.number = this.createdItem.number
            // data.status = this.createdItem.status
            data.remark = this.createdItem.remark
            data.name = this.createdItem.name

            update(data).then(response => {
              this.formSubmiting = false
              this.formVisible = false
              this.$message.success('操作成功')
              this.getList()
            })
          }
        }
      })
    },
    formatDate(now) {
      var year = now.getFullYear() //取得4位数的年份
      var month = now.getMonth() + 1 //取得日期中的月份，其中0表示1月，11表示12月
      var date = now.getDate() //返回日期月份中的天数（1到31）
      var hour = now.getHours() //返回日期中的小时数（0到23）
      var minute = now.getMinutes() //返回日期中的分钟数（0到59）
      var second = now.getSeconds() //返回日期中的秒数（0到59）
      return (
        year +
        '-' +
        (month < 10 ? '0' + month : month) +
        '-' +
        (date < 10 ? '0' + date : date) +
        ' ' +
        (hour < 10 ? '0' + hour : hour) +
        ':' +
        (minute < 10 ? '0' + minute : minute) +
        ':' +
        (second < 10 ? '0' + second : second)
      )
    }
  }
}
</script>
<style scoped>
.white-list {
  padding: 20px;
}
</style>
